package com.sunnyebuy.merchant.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.sunnyebuy.merchant.service.CustomerOrderService;

/**
 * <p>
 * Title: SerialNumberUtil.java
 * </p>
 * 
 * <p>
 * Description: com.sunnyebuy.merchant.util
 * </p>
 * 
 * <p>
 * Copyright: Copyright (c) 2008-2011 All rights reserved.
 * </p>
 * 
 * <p>
 * Created: 2011-12-29 下午4:11:09
 * </p>
 * 
 * @author Wenzhong Gu
 * 
 * @version 1.0
 */
public class SerialNumberUtil {

	private static final String ORDER_PREFIX = "EC";
	private static String lastOrderSn;

	static {
		// 订单编号
		CustomerOrderService customerOrderService = (CustomerOrderService) SpringUtil.getBean("customerOrderService");
		String lastOrderTx = customerOrderService.getLastOrderTx();
		if (lastOrderTx != null && "".equals(lastOrderTx.trim())) {
			lastOrderSn = lastOrderTx;
		}
	}

	/**
	 * 参数长度必须为20
	 * 
	 * @param str
	 * @return
	 */
	public static String addCheckNum(String str) {
		final String CHECKNUM_VER_CODE = "0213654897";
		final int[] CHECKNUM_SALT = { 1, 1, 2, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 2, 1, 2 };
		if (str != null && str.trim().length() == 17) {
			char[] id = str.toCharArray();
			long sum = 0;
			for (int i = 0; i < 17; i++) {
				sum += (long) (id[i] - '0') * CHECKNUM_SALT[i];
			}
			int iY = (int) (sum % 10);
			return ORDER_PREFIX + str + CHECKNUM_VER_CODE.substring(iY, iY + 1);
		} else {
			return null;
		}
	}
	//110910XXXXXXXXX
	public static synchronized String getLastOrderTx() {
		DateFormat df = new SimpleDateFormat("yyMMdd");
		Date today = new Date();
		String num = df.format(today) + "00000001";
		if (lastOrderSn != null && lastOrderSn.trim().length() == 15) {
			if (lastOrderSn.substring(2, 10).equals(df.format(today))) {
				long step = (long) (Math.random() * 9) + 7;
				num = String.valueOf(Long.parseLong(lastOrderSn.substring(2, 19)) + step);
				lastOrderSn = addCheckNum(num);
			} else {
				lastOrderSn = addCheckNum(num);
			}
		} else {
			lastOrderSn = addCheckNum(num);
		}
		return num;
	}

}